package net.ipinglun.presenters;

import com.loopj.android.http.AsyncHttpClient;
import com.loopj.android.http.AsyncHttpResponseHandler;

import net.ipinglun.activitys.NewsDetailActivity;
import net.ipinglun.models.NewsDetailBean;
import net.ipinglun.utils.Constants;

import org.apache.http.Header;
import org.json.JSONException;
import org.json.JSONObject;

public class NewsDetailPresenter {

    private NewsDetailActivity mDelegate;

    public NewsDetailPresenter(NewsDetailActivity context) {
        mDelegate = context;
    }

    public void getNewsDetail(String newsId) {

        String url = "http://api.wallstreetcn.com/v2/posts/" + newsId;

        final NewsDetailBean newsDetail = new NewsDetailBean();

        AsyncHttpClient client = new AsyncHttpClient();
        client.setTimeout(Constants.CONNECT_TIMEOUT);

        client.get(url, new AsyncHttpResponseHandler() {

            @Override
            public void onStart() {
                super.onStart();
                mDelegate.onLoadNewsDetailStart();
            }

            @Override
            public void onFinish() {
                super.onFinish();
                mDelegate.onLoadNewsDetailFinish();
            }

            @Override
            public void onFailure(int arg0, Header[] arg1, byte[] arg2,
                                  Throwable arg3) {

                mDelegate.onLoadNewsDetailFailure();
            }

            @Override
            public void onSuccess(int statusCode, Header[] headers, byte[] content) {
                String jsonStr = new String(content);

                try {
                    JSONObject jsonObj = new JSONObject(jsonStr);

                    newsDetail.title = jsonObj.getString("title");

                    String body = jsonObj.getString("content");
                    String html = "<html><link href='file:///android_asset/style.css' rel='stylesheet' type='text/css'/><head><title></title></head><body style='color:#333333;line-height:150%%;font-size:16px;'>body_content</body></html>";

                    newsDetail.content = html.replaceAll("body_content",  body).replaceAll("style=\"[^/]+px;\"", "");
                    System.out.println("html=" + newsDetail.content);

                } catch (JSONException e) {
                    e.printStackTrace();
                }

                mDelegate.onLoadNewsDetailSuccess(newsDetail);
            }

        });

    }
}
